package com.tmt.im.manager.config.beans;

import com.tmt.data.jpa.service.beans.UserInfoVo;
import com.tmt.im.manager.service.IMUserService;
import com.tmt.im.manager.service.IgniteService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import java.io.IOException;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/7/21 23:27
 * @Version 1.0
 **/
public class MyLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private final IgniteService igniteService;

    private final IMUserService imUserService;

    public MyLoginSuccessHandler(IgniteService igniteService, IMUserService imUserService) {
        this.igniteService = igniteService;
        this.imUserService = imUserService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (authentication instanceof OAuth2AuthenticationToken token) {
            Long id = token.getPrincipal().getAttribute("id");
            if (!igniteService.existByUserId(id)) {
                try {
                    UserInfoVo vo = new UserInfoVo();
                    vo.setId(id);
                    vo.setNickname(token.getPrincipal().getAttribute("nickname"));
                    vo.setPassword(token.getPrincipal().getAttribute("pwd"));
                    vo.setMobile(token.getPrincipal().getAttribute("mobile"));
                    vo.setDeviceIds(token.getPrincipal().getAttribute("deviceIds"));
                    vo.setDeviceType(token.getPrincipal().getAttribute("deviceType"));
                    imUserService.registerUser(vo);
                } catch (Exception ex) {
                }
            }
            //在这里清除在ignite中存在的登出用户信息。
            igniteService.registerLoginUser(id);
        }
        super.onAuthenticationSuccess(request, response, authentication);
    }

}
